package com.cykj.pos.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.controller.TestDTO.FileItem;
import com.cykj.pos.controller.TestDTO.HttpClientHandler;
import com.cykj.pos.domain.BizMerchant;
import com.cykj.pos.domain.BizMerchantEntry;
import com.cykj.pos.domain.BizMessageRecords;
import com.cykj.pos.domain.dto.BizAgentidAppkeyDTO;
import com.cykj.pos.mapper.IncomingPartsMapper;
import com.cykj.pos.service.*;
import com.cykj.pos.service.impl.BizMerchantReceiverServiceImpl;
import com.cykj.pos.util.PosOneUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author SunJinDuo
 * @date 2022/7/15
 * 方法名称： 规则1
 */
@Service
public class Rule_oneServiceImpl implements Rule_oneService {

    private static final Logger logger = LoggerFactory.getLogger(Rule_oneServiceImpl.class);

    @Autowired
    private IncomingPartsMapper incomingPartsMapper;

    @Autowired
    private IBizMerchantEntryService bizMerchantEntryService;

    @Autowired
    private IBizMerchantService bizMerchantService;

    @Autowired
    private IBizMerchantEntryService iBizMerchantEntryService;

    @Autowired
    private IBizPosMachineStatusRecordsService recordsService;

    @Autowired
    private IBizMessageRecordsService bizMessageRecordsService;

    @Autowired
    private IBizPosMachineService bizPosMachineService;
    @Autowired
    private BizMerchantReceiverServiceImpl bizMerchantReceiverService;

    @Transactional
    public AjaxResult newStartup(Long id) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = df.format(System.currentTimeMillis());
        logger.info("<<<<<------------------------->>>>> -");
        logger.info("<<<<<--- 规则一，开始时间：" + startTime + " --->>>>> -");
        logger.info("<<<<<------------------------->>>>> -");
        AjaxResult ajaxResult = AjaxResult.success("新商户报件");
        logger.info("<<<<<--- 收取到的id为：" + id + "。 --->>>>> -");
        BizMerchantEntry bizMerchantEntry2 = new BizMerchantEntry();
        bizMerchantEntry2.setId(id);
        //先更新一下报件信息
        bizMerchantEntry2.setFacerecognizeface("1");
        bizMerchantEntryService.updateizMerchantEntryFacerecognizeface(bizMerchantEntry2);
        //查询出刚才的报件信息
        BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.selectBizMerchantEntry(bizMerchantEntry2.getId());
        // String snCode = bizMerchantEntryService.selectBizMerchantEntrySn(bizMerchantEntry2.getId());
        //查询商户
        String snCode = bizMerchantEntry.getSn();
        logger.info("<<<<<------------------------->>>>> -");
        logger.info("<<<<<--------新 报 件 接 口----------->>>>> -");
        logger.info("<<<<<------------------------->>>>> -");
        BizMerchant bizMerchant = bizMerchantService.selectBizMerchantBySN(bizMerchantEntry.getSn());
        //  bizMerchantEntry.setSn(snCode);
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=add";
        Map<String, String> data = new HashMap<String, String>();
        data.put("phone", bizMerchantEntry.getPhone());// 手机号
        data.put("applicant", bizMerchantEntry.getApplicant());// 姓名
        data.put("provinceno", bizMerchantEntry.getProvinceno());// 省编号
        data.put("cityno", bizMerchantEntry.getCityno());// 城市编号
        data.put("areano", bizMerchantEntry.getAreano());// 区编号
        data.put("certificateno", bizMerchantEntry.getCertificateno());// 身份证
        data.put("certificatestartdate", bizMerchantEntry.getCertificatestartdate());// 身份证开始时间
        data.put("certificateenddate", bizMerchantEntry.getCertificateenddate());// 身份证结束时间
        data.put("bankcardaccount", bizMerchantEntry.getBankcardaccount());// 银行卡号
        data.put("fee_chl_id", bizMerchantEntry.getFeeChlId());// 费率终端id
        data.put("merchantname", bizMerchantEntry.getMerchantname());// 费率终端id
        data.put("mcccode", bizMerchantEntry.getMcccode());// 费率终端id
        if("10285".equals(bizMerchantEntry.getFeeChlId())){
            data.put("extra_value","300");// 附加费
            data.put("fee_chl_id", "111");// 费率终端id
        }else{
            data.put("extra_value","0");// 附加费
            data.put("fee_chl_id", bizMerchantEntry.getFeeChlId());// 费率终端id
        }
        data.put("sn", bizMerchantEntry.getSn());// 设备号
        data.put("mersource", "OUTMER");
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", generateSignature(data));
        Map<String, FileItem> fileItemMap = new HashMap<>();
        FileItem idcardHand = new FileItem();
        idcardHand.setFileName("手持身份证照");
        idcardHand.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem faceRecognizeFace = new FileItem();
        faceRecognizeFace.setFileName("人脸识别照");
        faceRecognizeFace.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem idcardFront = new FileItem();
        idcardFront.setFileName("身份证头像面");
        idcardFront.setFile(convertFileByUrl(bizMerchantEntry.getIdcardfront()));
        FileItem idcardBack = new FileItem();
        idcardBack.setFileName("身份证国徽面");
        idcardBack.setFile(convertFileByUrl(bizMerchantEntry.getIdcardback()));
        FileItem bankcardFront = new FileItem();
        bankcardFront.setFileName("银行卡正面照");
        bankcardFront.setFile(convertFileByUrl(bizMerchantEntry.getBankcardfront()));
        FileItem bankcardBack = new FileItem();
        bankcardBack.setFileName("银行卡背面照");
        bankcardBack.setFile(convertFileByUrl(bizMerchantEntry.getBankcardback()));
        fileItemMap.put("idcardHand", idcardHand);
        fileItemMap.put("faceRecognizeFace", faceRecognizeFace);
        fileItemMap.put("idcardFront", idcardFront);
        fileItemMap.put("idcardBack", idcardBack);
        fileItemMap.put("bankcardFront", bankcardFront);
        fileItemMap.put("bankcardBack", bankcardBack);
        logger.info("<<<<<--- 请求参数数据==data：" + data + "。 --->>>>> -");
        logger.info("<<<<<--- 请求需要的图片==fileItemMap：" + fileItemMap + "。 --->>>>> -");
        String result = HttpClientHandler.onRequest(url, data, fileItemMap);
        logger.info("<<<<<--- 返回值返回类型参数==result：" + result + "。 --->>>>> -");
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        Object b = jsonObject.getString("data");
        logger.info("<<<<<--- data：" + b + "。 --->>>>> -");
        if (retCode.equals("0")) {
            JSONObject dara1 = jsonObject.getJSONObject("data");
            String merchantNo = dara1.getString("merchant_no");
            bizMerchantEntry.setMerchantNo(merchantNo);// 存入商户编号
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            bizMerchantEntry.setCreateTime(format.format(date));
            bizMerchantEntry.setAgentid(bizAgentidAppkeyDTO.getAgentid());

            bizMerchantEntry.setCreateTime(format.format(new Date()));
            /***  在这里写新的 在另一个表里存sn还有报件的id  *****/
            iBizMerchantEntryService.insertBizEntrySn(bizMerchantEntry);
            // 存储商户信息
            int row = 0;
            //去更新这个表
            row = bizMerchantEntryService.upDateBizMerchantEntryMerchantNo(bizMerchantEntry);
            /****             ****/
            int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
            //插入消息通知
            BizMessageRecords bizMessageRecords = new BizMessageRecords();
            bizMessageRecords.setMsgUserId(bizMerchant.getUserId());
            bizMessageRecords.setMsgContent("SN:"+snCode+",审核成功");
            bizMessageRecords.setMsgStatus(0);
            bizMessageRecords.setMsgType(9);
            bizMessageRecords.setReadStatus(0);
            bizMessageRecords.setAdviceType(1);
            bizMessageRecordsService.save(bizMessageRecords);
            if (row > 0) {
                ajaxResult.put("data", true);
                ajaxResult.put("retMsge", retMsge);
            } else {
                ajaxResult.put("data", false);
                ajaxResult.put("retMsge", "报件失败");
            }
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
        } else {
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            ajaxResult.put("data", false);
            ajaxResult.put("retMsge", retMsge);
            BizMerchantEntry bizMerchantEntry3 = bizMerchantEntryService.selectBizMerchantEntry(bizMerchantEntry2.getId());
            if( bizMerchantEntry3.getMerchantNo()==null){
                //推送消息
                BizMessageRecords bizMessageRecords = new BizMessageRecords();
                bizMessageRecords.setMsgUserId(bizMerchant.getUserId());
                bizMessageRecords.setMsgContent("SN:"+snCode+",审核失败，原因:"+retMsge);
                bizMessageRecords.setMsgStatus(0);
                bizMessageRecords.setMsgType(9);
                bizMessageRecords.setReadStatus(0);
                bizMessageRecords.setAdviceType(1);
                bizMessageRecordsService.save(bizMessageRecords);
                //把错误信息附上
                bizMerchantEntryService.updateizMerchantEntryErroMessage(bizMerchantEntry2.getId(),retMsge);
            }
            return ajaxResult;
        }
        //查询商户状态
        String urls = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=load";
        JSONObject dara1 = jsonObject.getJSONObject("data");
        String merchantNo = dara1.getString("merchant_no");
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("merchant_no", merchantNo);
        dataMap.put("mersource", "OUTMER");
        dataMap.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        dataMap.put("key", bizAgentidAppkeyDTO.getKey());
        dataMap.put("sign", PosOneUtil.generateSignature(dataMap));
        String results = HttpClientHandler.noPictureRequest(urls, dataMap);
        logger.info("<<<<<--- 查询商户状态返回数据：" + results + "。 --->>>>> -");
        JSONObject parseObject = JSONObject.parseObject(results);
        String code = parseObject.getString("ret_code");
        if (code.equals("0")) {
            //获取审核状态
            JSONObject data1 = parseObject.getJSONObject("data");
            String proMerSub = data1.getString("pro_mer_sub");
            //更新商户入件状态
            iBizMerchantEntryService.updateMerchantEntry(merchantNo, proMerSub);
            if (proMerSub.equals("3")) {
                //更新激活表状态
                recordsService.updatePosRecordsStatus(snCode);
                //更新设备表
                bizPosMachineService.updatePosPosMachine(snCode);
                //查询流量费收取列表
                //bizFeesChargedService.timerGetChargeList(snCode);
            }
            String proMerSubName = data1.getString("pro_mer_sub_name");
            ajaxResult.put("retMsge", proMerSubName);
        }
        logger.info("<<<<<--- 规则一，结束 --->>>>> -");
        return ajaxResult;
    }

    @Transactional
    public String generateSignature(Map<String, String> data) {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyArray.length; i++) {
            String k = keyArray[i];
            if (data.get(k) != null) { // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim());
                if (i != keyArray.length - 1) {
                    sb.append("&");
                }
            }
        }
        return md5(sb.toString()).toUpperCase();
    }

    @Transactional
    public String md5(String inStr) {
        try {
            return DigestUtils.md5Hex(inStr.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误");
        }
    }

    @Transactional
    public File convertFileByUrl(String url) {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 如果是文件 ==》直接删除
     * 如果是目录 ==》必须先删除里面每一层目录里的所有文件，最后才能删除外层的目录
     * 原因：不为空的话 删不了
     */
    @Transactional
    public void deleteFile(File file) {
        if (file.exists()) {//判断路径是否存在
            if (file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                file.delete();
            } else {//不是文件，对于文件夹的操作
                //保存 路径D:/1/新建文件夹2  下的所有的文件和文件夹到listFiles数组中
                File[] listFiles = file.listFiles();//listFiles方法：返回file路径下所有文件和文件夹的绝对路径
                for (File file2 : listFiles) {
                    /*
                     * 递归作用：由外到内先一层一层删除里面的文件 再从最内层 反过来删除文件夹
                     *    注意：此时的文件夹在上一步的操作之后，里面的文件内容已全部删除
                     *         所以每一层的文件夹都是空的  ==》最后就可以直接删除了
                     */
                    deleteFile(file2);
                }
            }
            file.delete();
        } else {
            System.out.println("该file路径不存在！！");
        }
    }
}
